package org.sgsm.dungeon.service;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

import org.sgsm.dungeon.common.ServiceAbstractImpl;

import org.sgsm.dungeon.xsd.context.ContextType;
import org.sgsm.dungeon.xsd.user.UserCriteriaType;
import org.sgsm.dungeon.xsd.user.UserScenarioType;
import org.sgsm.dungeon.xsd.user.UserType;
import org.sgsm.dungeon.xsd.user.UserListType;
import org.sgsm.dungeon.xsd.user.UserKeyType;

public class UserManagerServiceImpl extends ServiceAbstractImpl
{
public UserType createUser(UserType pUserType , UserScenarioType pUserScenarioType , ContextType pContextType)
{
	UserType result = null;
	if( pUserType!= null)
	{
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.save(pUserType);
		tx.commit();
		session.refresh(pUserType);
		session.close();
		result = pUserType;
	}
	return result;
}
public void deleteUser(UserKeyType pUserKeyType , UserScenarioType pUserScenarioType , ContextType pContextType)
{
	if( pUserKeyType != null)
	{
		Session session = getSession();
		UserKeyType result =  (UserKeyType) session.get(UserKeyType.class, pUserKeyType.getId());
		if( result != null)
		{
			Transaction tx = session.beginTransaction();
			session.delete(result);
			tx.commit();
		}
		session.close();
	}
}
public UserListType findUser(UserCriteriaType pUserCriteriaType , UserScenarioType pUserScenarioType , ContextType pContextType)
{
	UserListType result = null;
	if( pUserCriteriaType != null)
	{
		result = new UserListType();
		Session session = getSession();
		Criteria crit = session.createCriteria(UserCriteriaType.class);
		crit.setMaxResults(10);
		List<UserType> resultCrit = crit.list();
		Iterator<UserType> it = resultCrit.iterator();
		while(it.hasNext())
		{
			result.getValues().add(it.next());
		}
	}
	return result;
}
public UserType getUser(UserKeyType pUserKeyType , UserScenarioType pUserScenarioType , ContextType pContextType)
{
	UserType result = null;
	if( pUserKeyType != null)
	{
		Session session = getSession();
		result =  (UserType) session.get(UserType.class, pUserKeyType.getId());
		session.close();
	}
	return result;
}
public UserType postUser(UserType pUserType , UserScenarioType pUserScenarioType , ContextType pContextType)
{
	UserType result = null;
	if( pUserType != null)
	{
		Session session = getSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(pUserType);
		tx.commit();
		session.close();
		session.refresh(pUserType);
		result = pUserType;
	}
	return result;
}
}
